
package net.vinote.smart.platform.service.filter;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.vinote.smart.platform.service.SRE;
import net.vinote.smart.platform.service.bean.DataWindowCatalog;
import net.vinote.smart.platform.service.bean.User;


public class AttachmentFilter implements Filter
{

	@Override
	public void destroy()
	{

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException
	{
		// 文件保存目录路径
		HttpServletRequest request = (HttpServletRequest) req;
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		String savePath = session.getServletContext().getRealPath("/")
				+ "WEB-INF" + File.separator + "attache" + File.separator
				+ user.getUserID();

		// 对同一用户的图片资源进行按表引用分类
		String doNo = request.getParameter("doNo");
		DataWindowCatalog catalog = SRE.getDataWindowCatalog(doNo);
		if (catalog != null)
		{
			savePath += File.separator + catalog.getMainTable().toLowerCase();
		}

		String path = request.getServletPath();
		if (path.startsWith("/attache/"))
		{
			String file = savePath
					+ File.separator
					+ path.substring("/attache/".length()).replace('/',
							File.separatorChar);
			File f = new File(file);
			if (!f.isFile())
			{
				f = new File(session.getServletContext().getRealPath("/")
						+ "comm" + File.separator + "images" + File.separator
						+ "empty.png");
			}
			if (f.isFile())
			{

				OutputStream out = resp.getOutputStream();
				byte[] buf = new byte[1024];
				FileInputStream fis = null;
				BufferedInputStream bis = null;
				int length;
				try
				{
					fis = new FileInputStream(f);
					bis = new BufferedInputStream(fis);
					while ((length = fis.read(buf)) > 0)
					{
						out.write(buf, 0, length);
						out.flush();
					}
					return;
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
				finally
				{
					if (bis != null)
					{
						bis.close();
					}
					if (fis != null)
					{
						fis.close();
					}
				}
			}
		}
		chain.doFilter(req, resp);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException
	{

	}

}
